//
//  ChartsVC.swift
//  TimeBoat
//
//  Created by bo wang on 2022/8/23.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import UIKit

class ChartsVC: AppBaseVC {
    
    var subject: ChartsSubject!
    
    @IBOutlet var topView: UIView!
    @IBOutlet var fakeNaviBar: UIView!
    @IBOutlet var fakeBackBtn: UIButton!
    @IBOutlet var fakeTitleLabel: UILabel!
    /// 分段内容是手动添加的，storyboard中预设置的无效
    @IBOutlet var dateSegmentView: UISegmentedControl!
    @IBOutlet var container: UIView!
    
    private var pageVC: UIPageViewController!
    private lazy var contentVCs: [ChartsContentsVC] = createContentsVCs()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.layoutIfNeeded()
        fakeTitleLabel.text = subject.title
        setupSegmentView()
        switchToContentsVC(at: subject.defaultGranularity)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        pageVC.fixGestureConflict(with: navigationController)
    }
    
    func switchToContentsVC(at granularity: DateGranularity) {
        if let index = subject.granularities.firstIndex(of: granularity) {
            switchToContentsVC(at: index)
        }
    }
    
    private func switchToContentsVC(at index: Int) {
        guard 0..<contentVCs.count ~= index else { return }
        
        var direction = UIPageViewController.NavigationDirection.forward
        if let vc = pageVC.viewControllers?.first as? ChartsContentsVC,
           let curVCIndex = contentVCs.firstIndex(of: vc) {
            direction = index > curVCIndex ? .forward : .reverse
        }
        let newVC = contentVCs[index]
        pageVC.setViewControllers([newVC], direction: direction, animated: true, completion: nil)
        dateSegmentView.selectedSegmentIndex = index
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? UIPageViewController {
            pageVC = vc
            pageVC.dataSource = self
            pageVC.delegate = self
        }
    }
    
    @IBAction func onSegmentDidChanged(_ seg: UISegmentedControl) {
        let index = seg.selectedSegmentIndex
        switchToContentsVC(at: index)
    }
}

extension ChartsVC: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let vc = viewController as? ChartsContentsVC,
              let index = contentVCs.firstIndex(of: vc) else { return nil }
        let nextIndex = index + 1
        guard 0..<contentVCs.count ~= nextIndex else { return nil }
        return contentVCs[nextIndex]
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let vc = viewController as? ChartsContentsVC,
              let index = contentVCs.firstIndex(of: vc) else { return nil }
        let previousIndex = index - 1
        guard 0..<contentVCs.count ~= previousIndex else { return nil }
        return contentVCs[previousIndex]
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        guard let vc = pageViewController.viewControllers?.first as? ChartsContentsVC,
              let index = contentVCs.firstIndex(of: vc) else { return }
        dateSegmentView.selectedSegmentIndex = index
    }
}

extension ChartsVC {
    
    private func setupSegmentView() {
        dateSegmentView.removeAllSegments()
        subject.granularities.enumerated().forEach { ele in
            dateSegmentView.insertSegment(withTitle: ele.element.title, at: ele.offset, animated: false)
        }
        dateSegmentView.setTitleTextAttributes([
            .foregroundColor: UIColor(hex: 0x040415, alpha: 0.5)!,
            .font: UIFont.systemFont(ofSize: 16)
        ], for: .normal)
        dateSegmentView.setTitleTextAttributes([
            .foregroundColor: UIColor(hex: 0xFF5E32)!
        ], for: .selected)
    }
    
    private func createContentsVCs() -> [ChartsContentsVC] {
        subject
        .granularities
        .compactMap { dg in
            let vc: ChartsContentsVC? = {
                switch subject {
                case .calories: return R.storyboard.charts.caloriesChartVC()
                case .distance: return R.storyboard.charts.distancesChartVC()
                case .steps: return R.storyboard.charts.stepsChartVC()
                case .heartRate: return R.storyboard.charts.heartRateChartVC()
                case .sleep: return R.storyboard.charts.sleepChartVC()
                case .bloodPressure: return R.storyboard.charts.bloodPressureChartVC()
                case .bloodOxygen: return R.storyboard.charts.bloodOxygenChartVC()
                case .temperature: return R.storyboard.charts.temperatureChartVC()
                case .sports: return R.storyboard.charts.sportsChartVC()
                case .none: return nil
                }
            }()
            vc?.granularitie = dg
            vc?.subject = subject
            vc?.contentInsetTop = self.topView.bounds.height
            vc?.view.frame = view.bounds
            return vc
        }
    }
}
